Numbers


In [1]:
"""
Multi-line
comment
"""
a = 7           # integer
b = 2.9         # float
c = 10 + 2j     # complex
d = a + b       # sum
e = a // b      # integer division
f = a % 5       # remainder of the division
g = a ** 3      # power
print(a, b, c, d, e, f, g)


7 2.9 (10+2j) 9.9 2.0 2 343

In [2]:
a = round(1.5)        # floor
b = abs(-10)          # absolute value
c = min(1, 2, 3)      # minimum value
print(a, b, c)


2 10 1

Create Strings


In [3]:
a = 'some string'
b = "another one"
d = "without escape ' "
c = 'with escape \' '
e = ' two \n lines '
f = '''Several
lines
of text'''

print(a, b, c, d, e, f)


some string another one with escape '  without escape '   two 
 lines  Several
lines
of text

Access / Modify strings


In [4]:
a = int('10')                    # convert to integer
b = len('string')                # length of string

c = 'LoremIpsumDolorSitAmet'

d = 'We ' + 'can ' + 'concatenate' + '\n'   # concatenate
e = 'We %s format %s' % ('can', '\n')       # format string
f = '>=<' * 20                              # replicate

print(a, b, c[0], c[1], c[2:5], d, e, f)


10 6 L o rem We can concatenate
 We can format 
 >=<>=<>=<>=<>=<>=<>=<>=<>=<>=<>=<>=<>=<>=<>=<>=<>=<>=<>=<>=<

Boolean


In [5]:
a = True
b = 1 > 2
c = 3 == 3
d = "abc" > "ABC"
e = 'a' in 'abcd'
f = 'o' not in 'abcd' 
g = f is True
print (a, b, c, d, e, f, g)


True False True True True True True

Lists


In [6]:
a = [1, 2, 3.5, 4+1j, 'str5', 'str6', 7, 8, 9, 10] # create list
b = a[0]                        # access one element
c = a[3:5]                      # access several elements
d = a[:5]                       # access several elements from begining
e = a[5:]                       # access several elements until end
f = a[:]                        # access all elements
g = a[:-2]                      # access several elements from begining
print (a)
print (b)
print (c)
print (d)
print (e)
print (f)
print (g)


[1, 2, 3.5, (4+1j), 'str5', 'str6', 7, 8, 9, 10]
1
[(4+1j), 'str5']
[1, 2, 3.5, (4+1j), 'str5']
['str6', 7, 8, 9, 10]
[1, 2, 3.5, (4+1j), 'str5', 'str6', 7, 8, 9, 10]
[1, 2, 3.5, (4+1j), 'str5', 'str6', 7, 8]
+---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1

Operations with lists


In [7]:
a = [0, 1, 2, 3.5, 4+1j, 'str5', 'str6', 7, 8, 9]
a[9] = 11                  # replace one element
a[0:2] = ['0', '1']        # replace several elements
del a[8]                   # remove first element
b = a[:4] + a[4:]          # concatenate two lists
c = [[1, 2, 3], [4, 5, 6]] # create nested list

c = [[1, 2, 3],            # nested list
     [4, 5, 6]]            # on multiple lines

d = [a[0:4], a[4:]]        # nested list from two sub-lists
e = [1, 2, 3] * 3          # replicate list
f = [[1, 2, 3]] * 3          # replicate list

print (a)
print (b)
print (c)
print (d)
print (e)
print (f)


['0', '1', 2, 3.5, (4+1j), 'str5', 'str6', 7, 11]
['0', '1', 2, 3.5, (4+1j), 'str5', 'str6', 7, 11]
[[1, 2, 3], [4, 5, 6]]
[['0', '1', 2, 3.5], [(4+1j), 'str5', 'str6', 7, 11]]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Tuples


In [8]:
a = (1,2,3)          # create tuple
b = 1,2,3            # create tuple
c, d, e = 1, 2, 3    # multiple assignment
f, g = c, d          # multiple assignment
f, g = g, f          # switch values
print (a,b,c,d,e,f,g)


(1, 2, 3) (1, 2, 3) 1 2 3 2 1

Dictionaries


In [9]:
a = {1: 123, 2.5: 'text', 'key3': [1,2,3]} # define dictionary

a = {    1 : 123,           # define dictionary 
       2.5 : 'text',        # on multiple lines
        'm': [1,2,3]}

b = a[1]                    # acces by key
c = a[2.5]                  # acces by key
d = a['m']                  # acces by key
e = {}                      # create empty dict
e['new key'] = 'new value'  # add key:value to the dict
e[0] = 'new value'  # add key:value to the dict

print (a)
print (b)
print (c)
print (d)
print (e)
print (e[0])


{1: 123, 2.5: 'text', 'm': [1, 2, 3]}
123
text
[1, 2, 3]
{'new key': 'new value', 0: 'new value'}
new value

Objects

Everything is object

  • Object is a container for data and functions
  • Data is called value (or attributes)
  • Functions are called methods

In [10]:
a = '   LoremIpsumDolorSitAmet   '
c = a.strip()

d = [0, 2, 1, 5, 4]
d.sort()
print (a)
print (c)
print (d)


   LoremIpsumDolorSitAmet   
LoremIpsumDolorSitAmet
[0, 1, 2, 4, 5]

Important methods of 'string'


In [11]:
# STRINGS
a = '   LaremIpsumDalarSitAmet   '
b = a.replace('a','o')
c = b.find('Lo')
d = '_'.join(['Larem', 'Ipsum', 'Dalar', 'Sit', 'Amet'])
                                  # a = '_'; a.join(...)
e = d.split('_')
f = a.replace('a', 'o').strip().split('m')

g = 'New {0} {1} {good}!'.format('style', 'is', good='better') 

print (a, '\n', b, '\n', c, '\n', d, '\n', e, '\n', f, '\n', g)


   LaremIpsumDalarSitAmet    
    LoremIpsumDolorSitAmet    
 3 
 Larem_Ipsum_Dalar_Sit_Amet 
 ['Larem', 'Ipsum', 'Dalar', 'Sit', 'Amet'] 
 ['Lore', 'Ipsu', 'DolorSitA', 'et'] 
 New style is better!

Importnat methods of 'list'


In [12]:
a = [0, 1, 2, 3, 4, 5, 6, 7, 8]
a.append(9)
a.extend([10,11])
a.insert(2, 200)
b = a.pop(3)
a.remove(5)
a.sort()
a.reverse()
print (a, b)


[200, 11, 10, 9, 8, 7, 6, 4, 3, 1, 0] 2

Importnat methods of 'dict'


In [13]:
a = {1: 123, 2.5: 'text', 'key3': [1,2,3]}
b = a.get(2, 'default')
c = a.pop('key3')
d = 2.5 in a
e = a.keys()
f = a.values()
print (a, b, c, d, e, f)


{1: 123, 2.5: 'text'} default [1, 2, 3] True dict_keys([1, 2.5]) dict_values([123, 'text'])

In [14]:
a[1] = 100
print (f)


dict_values([100, 'text'])

Pointers

Everything is a pointer to object

  • Data is stored in computer memory (RAM)
  • Pointer is address of the object in memory
  • Several pointers may point to the same object

In [15]:
a = [0, 1, 2]
b = a
b[0] = 10
print (a)


[10, 1, 2]

In [16]:
b = list(a)
d = tuple(a)
print (b, d )


[10, 1, 2] (10, 1, 2)

In [17]:
a = [1,2,3]
a[0] = 10
b = (1,2,3)
#b[0] = 10
print (a)


[10, 2, 3]

Functions are also objects pointers to objects


In [18]:
a = len               # let <a> be the len() function
print (a, a('some text'))


<built-in function len> 9

In [19]:
a = [0, 2, 3, 1]
b = a.sort          # let <b> be method of the list
a.append(-1)        # modify the list
b()                 # call the method, equals to a.sort()
print (a)


[-1, 0, 1, 2, 3]

Other useful built-in types


In [20]:
a = set([1,2,3,4,1,2,3,4])  # SET: unordered collection
b = set([3,4,5,6,3,4,5])    #      of distinct objects (unique)
c = a | b                   # join
d = a & b                   # intersect
print (a, b, c, d)


{1, 2, 3, 4} {3, 4, 5, 6} {1, 2, 3, 4, 5, 6} {3, 4}

In [21]:
f = open('test.txt', 'w')                    # open FILE
f.write('the first line\nthe second line\n') # write text
f.close()                                    # close
f = open('test.txt')                         # open again
print (f.readlines() )                         # read lines as list


['the first line\n', 'the second line\n']

In [22]:
# RANGE: list generated on-the-fly
r1 = range(5)         # number of elements
r2 = range(3, 15)     # first and last
r3 = range(3, 15, 2)  # first, last and step
a = list(r1)          # convert to list
b = r1[2]             # access element
c = r3[3:]            # get sub-range
d = len(r3)           # length of range
print (r1, a, b, c, d)


range(0, 5) [0, 1, 2, 3, 4] 2 range(9, 15, 2) 6

Modules, packages and scripts

+---------------------------------------+ | Python | | | | +---------------------------------+ | | | Packages (os) | | | | | | | | +---------------------------+ | | | | | Modules (path) | | | | | | | | | | | | +---------------------+ | | | | | | | Functions (exists) | | | | | | | | | | | | | | | +---------------------+ | | | | | +---------------------------+ | | | +---------------------------------+ | +---------------------------------------+

In [23]:
import os                            # import entire package
a = os.path.exists('some_file.txt')

import os.path                       # import module
a = os.path.exists('some_file.txt')

from os import path                  # import module
a = path.exists('some_file.txt')

from os.path import *           # import function
a = exists('some_file.txt')

from os.path import exists as xsts   # import function with nickname
a = xsts('some_file.txt')

Control flow


In [24]:
# simple IF. Notice 4-space intendation of a block!
a = 0
if a == 0:
    a += 1
    print ('OK, inside a block')
print (a, 'outside a block')


# IF with many choices. function values are tested
b = [0, 1, 2]
if a in b:
    print ('OK')
elif isinstance(a, str):
    print ('not OK')
else:
    print ('else')

    
# FOR loop over a list element
a = [0, 1, 2, 3, 4]
for i in a:
    print (i)

    
# FOR loop over a range
for i in range(5):
    print (i)

    
# Nested blocks
for i in range(10):
    if i > 5:
        print (i)

        
# List comprehension
a = []
for i in range(10):
    b = i**2
    a.append(b)
# Equal TO:
a = [i**2 for i in range(10)]


OK, inside a block
1 outside a block
OK
0
1
2
3
4
0
1
2
3
4
6
7
8
9

In [ ]: